﻿#ifndef YCBASETASK_H
#define YCBASETASK_H
#include <QDateTime>
#include <QObject>

QT_BEGIN_NAMESPACE
class QTimer;
QT_END_NAMESPACE

namespace yc {

class Task : public QObject
{
    Q_OBJECT

public:
    enum Status { NOT_START_STATUS, RUNNING_STATUS, FAILED_STATUS, FINISHED_STATUS };

    explicit Task(int timeout, QObject* parent = nullptr);
    Task(int id, bool auto_delete, int timeout, QObject* parent);
    virtual ~Task() = default;

    int id() const { return id_; }
    bool autoDelete() const { return auto_delete_; }
    int priority() const { return priority_; }
    void setPriority(int priority) { priority_ = priority; }
    bool isRunning() const { return status_ == RUNNING_STATUS; }
    bool isFailed() const { return status_ == FAILED_STATUS; }
    bool isFinished() const { return status_ == FINISHED_STATUS; }
    int timeout() const;
    void startTimeoutTimer(int timeout);
    void stopTimeoutTimer();
    void start();
    void terminate();

    virtual QString statusMessage() const;
    virtual qint64 elapsedMSecs() const;
    virtual qint64 evaluateTotalMSecs() const;

Q_SIGNALS:
    void aboutToStart();
    void finished();
    void failed(int error, const QString& message);

private:
    virtual void startImpl() = 0;
    virtual void terminateImpl() { }
    virtual void onTimeout() { }

    int id_;
    bool auto_delete_;
    int priority_;
    Status status_;
    QTimer* timer_;
    QDateTime start_time_;
    QDateTime end_time_;
};
} // namespace yc

#endif // YCBASETASK_H
